﻿using System;
using System.Linq;

namespace Utils.Buffer
{
    public static class ByteUtil
    {
        /// <summary>
        /// 拷贝为新的数组
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static byte[] CopyToNew(this byte[] bytes, int length)
        {
            return CopyToNew(bytes, 0, length);
        }

        /// <summary>
        /// 拷贝为新的数组
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="offset">开始位置</param>
        /// <param name="length">长度</param>
        /// <returns></returns>
        public static byte[] CopyToNew(this byte[] bytes, long offset, int length)
        {
            if (bytes.Length < offset + length) throw new IndexOutOfRangeException("bytes");
            byte[] destinationArray = new byte[length];
            Array.Copy(bytes, offset, destinationArray, 0, length);
            return destinationArray;
        }

        /// <summary>
        /// 转int32
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static int ToInt32(this byte[] bytes)
        {
            return bytes.Select(a => (int)a).Aggregate((a, b) => (a << 8) + b);
        }

        /// <summary>
        /// 转int64
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static long ToInt64(this byte[] bytes)
        {
            return bytes.Select(a => (long)a).Aggregate((a, b) => (a << 8) + b);
        }

        /// <summary>
        /// 转字节数组
        /// </summary>
        /// <param name="value"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static byte[] ToBytes(this int value, int length = 4)
        {
            return ToBytes((long)value, length);
        }

        /// <summary>
        /// 转字节数组
        /// </summary>
        /// <param name="value"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static byte[] ToBytes(this long value, int length = 8)
        {
            var bytes = new byte[length];
            for (int i = 0; i < length; i++)
            {
                // 写入一个字节
                bytes[i] = (byte)(value >> (length - i - 1) * 8 & 0xff);
            }
            return bytes;
        }
    }
}
